"Pluster Config "
import ConfigParser
import os.path
from service.exception import  *


class OrderedConfigParser(ConfigParser.ConfigParser):
    """Write all sections and options to an .ini file in sorted order."""
    def ordered_write(self, fp, name, section):
        """Write out all of a section's options in sorted order."""
        fp.write("[%s]\n" % name)
        s_items = list(section.items())  # sorted items
        s_items.sort()
        for (key, value) in s_items:
            if key != "__name__":
                fp.write("%s = %s\n" %
                         (key, str(value).replace('\n', '\n\t')))
        fp.write("\n")

    def write(self, fp):
        """Write a sorted .ini representation of the configuration state."""
        if self._defaults:
            self.ordered_write(fp, ConfigParser.DEFAULTSECT, self._defaults)
        s_sections = list(self._sections)  # sorted sections
        s_sections.sort()
        for section in s_sections:
            self.ordered_write(fp, section, self._sections[section])


class PConfig:
    """Pluster config class. Read config file and environment variables
    Usage:
    PConfig()
    cfg=PConfig.attribute
    cfg
    """
    attribute = None
    def __init__(self):
        "init"
        self.config = OrderedConfigParser()
        try:
            self.cfg_file = open("pluster.cfg")
            self.config.readfp(self.cfg_file)
            #xml-rpc
            self.pool_size = self.config.getint('xmlrpc', \
                                                    'task_poolsize')
            self.reuse = self.config.getboolean('xmlrpc', 'reuse')
            self.port_start = self.config.getint('xmlrpc', 'port_start')

            #debug config
            self.dbg_level = self.config.getint('debug', 'debuglevel')

            #main Server
            self.ms_port = self.config.getint('main_server', 'port')
            self.ms_net = self.config.get('main_server', 'net')
            self.ms_address = self.config.get('main_server', \
                                                  'address')
            self.rrd_path = self.config.get('rrd', 'rrd_path')

            #cluster
            self.cluster_name = self.config.get('cluster', 'name')
            self.cluster_total_node = self.config.getint('cluster', \
                                                             'total_node')
            self.cluster_mail = self.config.get('cluster', 'mail')
            self.cluster_passwd = self.config.get('cluster', 'passwd')
            self.cluster_smtp = self.config.get('cluster', 'smtp')
            self.cluster_send_to = self.config.get('cluster', \
                                                       'send_to')
            #logger
            self.logger_view_limit = self.config.getint('logger', \
                                                         'view_limit')
            self.logger_file_on = self.config.getboolean('logger', 'file_on')
            self.logger_file_name = self.config.get('logger','file_name')
            self.logger_file_size_limit = self.config.getint('logger','file_size_limit')

            self.logger_mail_on = self.config.getboolean('logger','mail_on')

            #node
            self.node_net = self.config.get('node', 'net')
            self.node_port = self.config.getint('node', 'port')
            PConfig.attribute = self

        except IOError,detail:
            #print "Read pluster.cfg file error, \
            #Check pluster.cfg exist", detail
            raise
        except Exception:
            # print "PConfig error, Check attribute exist"
            raise

    def add_node(self):
        "record adding a rrd file "
        cfg_file = open('pluster.cfg','w')
        self.cluster_total_node += 1
        self.config.set('cluster', 'total_node', self.cluster_total_node)
        self.config.write(cfg_file)
        cfg_file.close()

    def read_user(self):
        """read user section to get user name and desc

        return a list of (user name,user describtion)"""
        try:
            return self.config.items('user')
        except ConfigParser.NoSectionError:
            self.config.add_section('user')
            return self.config.items('user')

    def remove_user (self, name):
        """remove user from config file """
        cfg_file = open('pluster.cfg','w''')
        if self.config.remove_option('user', name):
            self.config.write(cfg_file)
            cfg_file.close()
        else:
            #print "Can not find %s in user section"%name
            raise PConfigNoUser


    def get_user_list(self):
        """return a list of user name except cluster"""
        try:
            user_list = self.config.options('user')
            cluster = self.cluster_name
            user_list.remove(cluster)
        except ValueError:
            #print "No cluster_name in user section,check pluster.cfg"
            raise PConfigNoUser
        return user_list

    def read_desc(self, name):
        "return user description "
        try:
            return self.config.get('user', name)
        except:
            raise PConfigNoUser(name)

    def add_user(self, name, desc):
        "add user name and desc to user section"
        cfg_file = open('pluster.cfg', 'w')
        self.config.set('user', name, desc)
        self.config.write(cfg_file)
        cfg_file.close()

    def check_rrd_exist(self):
        """check each user has a rrd file
        return a list of user who doesn't have rrd file """
        user=self.get_user_list()
        path=self.rrd_path
        return [i for i in user if not os.path.exists(path+i+'.rrd')]



